<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id 商品id
 * @param type $width 生成缩略图的宽度
 * @param type $height 生成缩略图的高度
 */

use OSS\Core\OssException;
use OSS\OssClient;
use Qcloud\Cos\Client;

/**
 * 微信浏览器判断
 */
function is_weixin()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

/**
 * 添加订单
 */
function createOrder($order_no, $price, $open_id, $act_id)
{
    $data = [
        'act_id' => $act_id,
        'order_no' => $order_no,
        'price' => $price,
        'open_id' => $open_id,
        'order_state' => 0,
        'pay_time' => time(),
    ];
    $id = db('order')->insertGetId($data);
    return $id;
}

/**
 * 更新订单
 */
function updateOrder($order_no, $price, $open_id, $act_id)
{
    $data = [
        'act_id' => $act_id,
        'order_no' => $order_no,
        'price' => $price,
        'open_id' => $open_id,
        'order_state' => 0,
        'pay_time' => time(),
    ];
    $id = db('order')->where(['act_id' => $act_id])->update($data);
}

/**
 * @param $user_id
 * @return string
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function update_user_token($user_id)
{
    $token = generator_token();
    db('user_token')->where(['uid' => $user_id])->update(['token' => $token]);
    return $token;
}

/**  每次登录更新 token
 * @param $user_id
 * @return string
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function update_admin_token($user_id)
{
    $token = generator_token();
    db('admin')->where(['id' => $user_id])->update(['token' => $token,'updatetime'=>time()]);
    return $token;
}

function generator_token()
{
    return md5(\uniqid(md5(microtime(true)), true));
}

/**
 * 过滤emoji表情
 * @param $str
 * @return string|string[]|null
 */
function filter_Emoji($str)
{
    $str = preg_replace_callback( //执行一个正则表达式搜索并且使用一个回调进行替换
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);

    return $str;
}

/**
 * 图片上传阿里云OSS
 * @param $fileName
 * @param $filePath
 */
function ailOssUpFile($fileName, $filePath)
{
    try {
        $accessKeyId = config("ali.OSS_CONFIG")["KEY_ID"];
        $accessKeySecret = config("ali.OSS_CONFIG")["KEY_SECRET"];
        $endpoint = config("ali.OSS_CONFIG")["END_POINT"];
        $bucket = config("ali.OSS_CONFIG")["BUCKET"];
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        return $ossClient->uploadFile($bucket, $fileName, $filePath);
    } catch (OssException $e) {
        print $e->getMessage();
    }
}

function txOssUpFile($saveFileName, $local_path)
{
    $ossConfig = config("wechat.OSS_CONFIG");

    $cosClient = new Client(
        array('region' => "gz",
            'credentials' => array(
                'secretId' => $ossConfig["SECRET_ID"],
                'secretKey' => $ossConfig["SECRET_KEY"]
            )
        )
    );
    //上传文件流
    try {
        $result = $cosClient->putObject(
            array(
                'Bucket' => $ossConfig["BUCKET"],
                'Key' => $saveFileName,
                'Body' => fopen($local_path, 'rb')
            )
        );
        return $result["ObjectURL"];
    } catch (\Exception $e) {
        print $e;
    }
}


function httpWurl($url, $params, $method = 'GET', $header = array(), $multi = false)
{
    date_default_timezone_set('PRC');
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_COOKIESESSION => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_COOKIE => session_name() . '=' . session_id(),
    );
    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            // 链接后拼接参数  &  非？
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) throw new Exception('请求发生错误：' . $error);
    return $data;
}

function getPage($page, $listRows, $total)
{
    $pages['page'] = $page;
    $pages['listRows'] = $listRows;
    $pages['total'] = $total;
    return $pages;
}

function p($data)
{
    print_r($data);exit;
}


/*
 * 获取文章评分 && 指数  弃用
 * */
function getScore()
{
    $list = db('article')->where('status',1)->field('id')->select();
    foreach ($list as $v){
        $data['score'] = db('graded')->where('aid',$v['id'])->avg('score');
        $data['look'] = db('graded')->where('aid',$v['id'])->count();
        db('article')->where('id',$v['id'])->update($data);
    }
}

/*
 * 根据文章id && categories_id 获取文章列表
 * */
function get_a_list($aid,$type=false,$page=1,$listRows=10,$term=1)
{
    $where = array();
    if ($type){
        $where['categories_id'] = $type;
    }
    if ($term == 1){
        $where['grade_status'] = 2;
    }
    if ($term == 2){
        $where = array();
    }
    $field = 'id,title,images,address,words,abstract,score,look,grade_id,spotname';
    $data = db('article')->where($where)->where('id','in',$aid)->field($field)->page($page,$listRows)->select();
    $total = db('article')->where($where)->where('id','in',$aid)->count();
    return (['list' => $data, 'total' => $total]);
}

/*
 *把数组中的图片转成数组
 * */
function json_array(array $arr)
{
    foreach ($arr as $k=>$v){
        $arr[$k]['images'] = json_decode($v['images']);
    }
    return $arr;
}


/*
 *判断用户是否给评论点赞
 *
 * */

function is_u_like($cid,$uid)
{
    $where = ['modular'=>'comment','uid' => $uid,'pid' => $cid];
    $list = db('collection')->where($where)->find();
    return empty($list) ? 0 : 1;
}


/*
 * 去 字符串空格
 */
function trim_str($str)
{
    return preg_replace("/\s|　/","",$str);
}